﻿using CommonUtil;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UDPTester
{
    public partial class FormTemplate : Form
    {
        public string SelectedString { get; set; }

        private BindingList<Template> TemplateList;
        private readonly string FilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TemplateList.xml");

        public FormTemplate()
        {
            InitializeComponent();
        }

        private void FormTemplate_Load(object sender, EventArgs e)
        {
            try
            {

                TemplateList = XmlHelper.XmlDeserializeFromFile<BindingList<Template>>(FilePath, Encoding.UTF8);
            }
            catch
            {
                TemplateList = new BindingList<Template>();
            }

            this.dataGridTemplates.DataSource = TemplateList;
        }

        private void menuAdd_Click(object sender, EventArgs e)
        {
            FormTemplateAdd templateAdd = new FormTemplateAdd();
            if (templateAdd.ShowDialog() == DialogResult.OK)
            {
                TemplateList.Add(templateAdd.Template);
                XmlHelper.XmlSerializeToFile(TemplateList, FilePath, Encoding.UTF8);
            }
        }

        private void menuRemove_Click(object sender, EventArgs e)
        {
            if (dataGridTemplates.SelectedRows != null)
            {
                TemplateList.RemoveAt(dataGridTemplates.SelectedRows[0].Index);
                XmlHelper.XmlSerializeToFile(TemplateList, FilePath, Encoding.UTF8);
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (dataGridTemplates.SelectedRows != null)
            {                
                this.SelectedString = TemplateList[dataGridTemplates.SelectedRows[0].Index].Content;

                this.DialogResult = DialogResult.OK;
                this.Close();
            }          
        }
    }
}
